# -*- coding: utf-8 -*-

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext, TemplateDoesNotExist
from django import forms
from django.forms import widgets
from django.conf import settings
from django.core import mail
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.utils.safestring import SafeUnicode
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_protect

import captcha

class ContactForm(forms.Form):
    """Contact form"""

    subject = forms.CharField(label=_('Subject'),
                              max_length=100)
    message = forms.CharField(widget=widgets.Textarea(attrs={'rows':10, 'cols':55}), # width set at 55 cols so that it does not overun page dimensions on a 800x600 screen.
                              label=_('Message'),
                              max_length=2000)
    email = forms.EmailField(label=_('Your email address'),
                             required=False,
                             help_text=_('Please enter your email address if you want a reply to your message.'))

@csrf_protect
def contact(request):
    """Contact page. Takes a message & sends it by email to the webmaster."""

    html_captcha = None
    captcha_is_valid = True
    UseRecaptcha = settings.EXTERNAL_RECAPTCHA and not request.user.is_authenticated()

    if request.method == 'POST':
        if UseRecaptcha:
            # Check the captcha
            check_captcha = captcha.submit(request.POST.get('recaptcha_challenge_field', None),
                                           request.POST.get('recaptcha_response_field', None),
                                           settings.RECAPTCHA_PRIVATE_KEY,
                                           request.META['REMOTE_ADDR'])
            if not check_captcha.is_valid:
                # Captcha is wrong show a error message in the template.
                captcha_is_valid = False
        form = ContactForm(request.POST)
        if form.is_valid() and captcha_is_valid:
            # Send email.
            site = Site.objects.get_current()
            if site.domain.startswith('www.'):
                SiteDomain = site.domain[4:]
            else:
                SiteDomain = site.domain

            try:
                EmailRecipientList = settings.CONTACT_EMAIL
            except:
                # no custom email recipients defined, use default value.
                EmailRecipientList = [email for name, email in settings.MANAGERS]

            # If user left a return email address, use that in the 'Reply-To:' field
            # Note that we use a Reply-To field. Originally this was coded to use the 
            # 'From' field, but this caused a problem when (for example) someone entered a
            # Hotmail address, and the recipient list included another Hotmail address.
            # Hotmail quite logically complained about receiving emails with a 
            # 'From: ...@hotmail.com' in the headers.
            if form.cleaned_data['email']:
                headers = {'Reply-To': form.cleaned_data['email']}
            else:
                headers = {} 

            # Format message
            message = u'THIS MESSAGE WAS SENT FROM THE CONTACT PAGE AT %s.\n' % (site.domain)
            if not form.cleaned_data['email']:
                message += u'THE PERSON DID NOT GIVE THEIR EMAIL ADDRESS.\n'
            message += '###\n' + form.cleaned_data['message']

            email = mail.EmailMessage(subject=form.cleaned_data['subject'],
                                      body=message,
                                      from_email='contact-page@'+SiteDomain,
                                      to=EmailRecipientList,
                                      headers=headers)
            email.send(fail_silently=False)
            return HttpResponseRedirect(reverse(thanks))
    else:
        # Allow links from other parts of the website to pre-set the subject line.
        subject = request.GET.get('subject', None)
        form = ContactForm(initial={'subject': subject})
    
    # Generate a new captcha every time we display this page.
    if UseRecaptcha:
        # Only generate a CAPTCHA for the production site.
        html_captcha = SafeUnicode(captcha.displayhtml(settings.RECAPTCHA_PUB_KEY))

    context = {'form': form,
               'html_captcha': html_captcha,
               'captcha_is_valid': captcha_is_valid}
    # Allow end user to put in their own (customised) template.
    try:
        return render_to_response('contact-recaptcha/custom_contact.html', context, context_instance=RequestContext(request))
    except TemplateDoesNotExist:
        return render_to_response('contact-recaptcha/contact.html', context, context_instance=RequestContext(request))

def thanks(request):
    """After a successful message is sent by email, display a thank you message to the visitor."""

    # The default setting is to send the visitor to the homepage after sending a message.
    # This behaviour can be overriden in CONTACT_NEXT_URL
    try:
        next = settings.CONTACT_NEXT_URL
    except:
        next = '/'
    return render_to_response('contact-recaptcha/thanks.html', {'next': next},
                              context_instance=RequestContext(request))







